package member

import (
	"errors"
	"gorm.io/gorm"
	"shopstar/global"
	"shopstar/models"
	"shopstar/models/member"
	"shopstar/util"
)

type Member struct{} // 快速实现接口 ctrl + i

var MemeberService = new(Member)

func (service *Member) FindMemberUsername(username string) (*member.Member, error) {
	model := new(member.Member)
	// 返回的是查询的错误信息
	err := models.DB.Where("username = ?", username).First(model).Error
	if err == gorm.ErrRecordNotFound { // 没有查到相关数据
		return model, global.ErrGormRecordNotFound
	}

	if err != nil {
		return model, errors.New("系统错误")
	}
	return model, nil
}

func (service *Member) Register(username, password, phone string) (*member.Member, error) {
	model := new(member.Member)

	_, err := service.FindMemberUsername(username)

	if err != nil && err != global.ErrGormRecordNotFound {
		return model, err
	}

	if err == nil {
		return model, global.ErrErrUsernameExist
	}

	pw, err := util.GenPasswordHash(password)
	if err != nil {
		return model, global.ErrPasswordHash
	}
	// 写入数据库
	model = &member.Member{
		Id:       models.WUID(),
		Username: username,
		Password: string(pw),
		Status:   1,
		Phone:    phone,
	}

	if err = models.DB.Create(model).Error; err != nil {
		return model, err
	}

	return model, nil
}

// 登录
func (service *Member) Login(username, password string) (*member.Member, error) {
	model, err := service.FindMemberUsername(username)
	if err != nil {
		return nil, err
	}
	if util.ValidatePasswordHash(password, model.Password) {
		return model, nil
	}
	return nil, global.ErrPassword
}

// AddMemberAddress 添加用户地址
func (service *Member) AddMemberAddress(userid, consigner, phone string, provinceId, cityId, districtId int, address string) error {
	model := &member.MemberAddress{
		UserId:     userid,
		Consigner:  consigner,
		Phone:      phone,
		ProvinceId: provinceId,
		CityId:     cityId,
		DistrictId: districtId,
	}

	return models.DB.Create(model).Error
}

// DefaultMemberAddress 查询用户默认地址
func (service *Member) DefaultMemberAddress(userId string) (address member.MemberAddress, err error) {
	err = models.DB.Where("user_id = ? && is_default = 1 ", userId).First(&address).Error
	return
}
